package services

import (
	"errors"
	"gitee.com/phpdi/ant-api/entitys"
	utils2 "gitee.com/phpdi/ant-api/utils"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/utils"
	"time"
)

type userService struct {

}

//用户服务单例对象
var UserService *userService
func init()  {
	UserService=new(userService)
}


//用户列表
func (this *userService)List(search *entitys.SearchUser)(err error)  {
	var users []entitys.User

	q := Orm().QueryTable(TableName("user"))
	if search.Params != "" {
		q = q.Filter("name__contains", search.Params)
	}

	_, err = q.Limit(search.PageSize).Offset(search.Offset()).All(&users)

	search.SetSliceData(users)

	return
}


//通过用户id 获取用户信息
func (this *userService)One(userId uint32)(user entitys.User,err error)  {
	user.Id=userId
	err=Orm().Read(&user)
	return
}

//通过用户名 获取用户信息
func (this *userService)GetUserByName(name string) (user entitys.User,err error)  {
	user.UserName=name
	err=Orm().Read(&user,"UserName")
	return
}

//用户添加
func (this *userService)Add(tran *Transactor,user entitys.User) (userId int64,err error)  {
	err = tran.Transaction(func(o orm.Ormer) error {

		//检查角色名重复
		if _, ok := Repeat(&user, TableName("user"), "Id", "UserName"); ok {
			return errors.New("用户账号重复")
		}

		//密码处理
		user.Salt=string(utils.RandomCreateBytes(16))
		user.Password=utils2.Md5("123456"+user.Salt)

		//添加
		user.CreateTime = time.Now()
		user.UpdateTime = time.Now()
		if userId, err = o.Insert(&user);err != nil {
			logs.Info("用户添加:",err)
			return errors.New("添加用户失败")
		}

		return nil
	})

	return

}

//角色编辑
func (this *userService) Edit(tran *Transactor,user entitys.User) (err error) {

	err= tran.Transaction(func(o orm.Ormer) error {

		if user.Id ==0 {
			return errors.New("用户ID缺失.")
		}

		//检查角色名重复
		if _, ok := Repeat(&user, TableName("user"), "Id", "Name"); ok {
			return errors.New("用户名称重复")
		}

		//编辑
		user.UpdateTime = time.Now()
		if _, err = o.Update(&user,utils2.GetNotZeroFields(user)...);err != nil {
			return errors.New("编辑用户失败")
		}

		return nil
	})

	return err
}


